import { message } from 'ant-design-vue'
import { api, siteAPI } from '@/api/index.js'
import { ref } from 'vue'
export const hasUserInteracted = ref(false)
const detectUserInteraction = () => {
  hasUserInteracted.value = true
  document.removeEventListener('click', detectUserInteraction)
  document.removeEventListener('keydown', detectUserInteraction)
}

// 添加事件监听器
// document.addEventListener('click', detectUserInteraction)
// document.addEventListener('keydown', detectUserInteraction)
// // 在播放音频前检查
// if (hasUserInteracted.value) {
//   props.riskAudio.play().catch(error => {
//     console.error('播放失败:', error)
//   })
// } else {
//   console.warn('用户尚未与页面交互，无法播放音频')
// }
export async function handleAPI (res, callback) {
  try {
    if (res.success) {
      if (res.data.length == 0) {
        message.info('暂无数据')
        return
      }
      if (typeof callback === 'function') {
        callback()
      }
    } else {
      message.error(res.message || '接口异常')
    }
  } catch (error) {
  }
}

export async function apiGet (url, params = {}, errorMessage = '请求错误') {
  try {
    const response = await api.get(url, { params })
    return response
  } catch (error) {
    console.error(errorMessage)
    message.error(errorMessage)
    return null
  }
}

export async function siteAPIGet (url, params = {}, errorMessage = '请求错误') {
  try {
    const response = await siteAPI.get(url, { params })
    return response
  } catch (error) {
    console.error(errorMessage)
    message.error(errorMessage)
    return null
  }
}

export async function apiPost (url, params = {}, errorMessage = 'An error occurred') {
  try {
    const response = await api.post(url, params)
    return response
  } catch (error) {
    message.error(errorMessage)
    return null
  }
}

export function serializeForm (data) {
  return Object.keys(data)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
    .join('&')
}

// 设置 Cookie 函数
export function setCookie (name, value, days) {
  let expires = ''
  if (days) {
    const date = new Date()
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000))
    expires = '; expires=' + date.toUTCString()
  }
  document.cookie = name + '=' + (value || '') + expires + '; path=/'
}

export function formatDateAll(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export function getNestedField (item, field) {
  const fields = field.split('.')
  let current = item

  for (let i = 0; i < fields.length; i++) {
      if (current[fields[i]] === undefined) {
        // 若嵌套属性不存在，返回 undefined
          return undefined
      }
      current = current[fields[i]]
  }
  return current
}

export function debounce (func, wait) {
  let timeout
  return function (...args) {
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      func.apply(this, args)
    }, wait)
  }
}

export const siteUrl = location.hostname === 'localhost' || location.hostname === '127.0.0.1' ? 'http://222.75.48.36:8080' : window.location.origin
